﻿using System.Collections;
using System.Diagnostics;
using System.Xml;
using System.Text;
using CJiaBao.Core.Utils;

namespace Core.Sdk.WeiXin.Tool
{
    /** 
    '============================================================================
    'api说明：
    'getKey()/setKey(),获取/设置密钥
    'getParameter()/setParameter(),获取/设置参数值
    'getAllParameters(),获取所有参数
    'isTenpaySign(),是否正确的签名,true:是 false:否
    'isWXsign(),是否正确的签名,true:是 false:否
    ' * isWXsignfeedback判断微信维权签名
    ' *getDebugInfo(),获取debug信息
    '============================================================================
    */

    public class ResponseHandler
    {
        // 密钥 
        private string key;
        // 参与签名的参数列表
        private static string SignField = "appid,appkey,timestamp,openid,noncestr,issubscribe";
        // 微信服务器编码方式
        private string charset = "gb2312";


        //protected Hashtable parameters;
        private Hashtable xmlMap;

        private XmlDocument xmlDoc;
        //获取页面提交的get和post参数
        public ResponseHandler()
        {
            xmlMap = new Hashtable();
        }
        public ResponseHandler(string formBody)
        {

            xmlMap = new Hashtable();
            if (!string.IsNullOrEmpty(formBody))
            {
                xmlDoc = new XmlDocument();
                xmlDoc.XmlResolver = null;
                xmlDoc.LoadXml(formBody);
                Trace.TraceInformation(xmlDoc.OuterXml);
                XmlNode root = xmlDoc.SelectSingleNode("xml");
                XmlNodeList xnl = root.ChildNodes;

                
                foreach (XmlNode xnf in xnl)
                {
                    xmlMap.Add(xnf.Name, xnf.InnerText);
                }
            }
        }

        public ResponseHandler(string formBody, string rootNode)
        {
            InitXml(formBody, rootNode);
        }

        public void LoadFromUrl(string formBody)
        {
            var nameValues = formBody.Split('&');
            foreach (var item in nameValues)
            {
                var arr = item.Split('=');
                xmlMap.Add(arr[0], arr[1]);
            }
        }

        public XmlDocument GetDocument()
        {
            return xmlDoc;
        }

        private void InitXml(string formBody, string rootNode)
        {
            xmlMap = new Hashtable();
            if (!string.IsNullOrEmpty(formBody))
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.XmlResolver = null;
                xmlDoc.LoadXml(formBody);
                Trace.TraceInformation(xmlDoc.OuterXml);
                XmlNode root = xmlDoc.SelectSingleNode(rootNode);
                XmlNodeList xnl = root.ChildNodes;

                foreach (XmlNode xnf in xnl)
                {
                    xmlMap.Add(xnf.Name, xnf.InnerText);
                }
            }
        }

        #region 参数=======================================
        /// <summary>
        /// 初始化加载
        /// </summary>
        public virtual void init()
        {
        }

        /// <summary>
        /// 获取密钥
        /// </summary>
        /// <returns></returns>
        public string getKey()
        {
            return key;
        }

        /// <summary>
        /// 设置密钥
        /// </summary>
        /// <param name="key"></param>
        public void setKey(string key)
        {
            this.key = key;
        }

        /// <summary>
        /// 获取参数值
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public string getParameter(string parameter)
        {
            var s = (string)xmlMap[parameter];
            return s ?? "";
        }

        /// <summary>
        /// 设置参数值
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="parameterValue"></param>
        public void setParameter(string key, string parameterValue)
        {
            //if (parameter != null && parameter != "")
            //{
            //    if (parameters.Contains(parameter))
            //    {
            //        parameters.Remove(parameter);
            //    }

            //    parameters.Add(parameter, parameterValue);
            //}
            if (xmlMap.ContainsKey(key))
            {
                xmlMap[key] = parameterValue;
            }
            else
                xmlMap.Add(key, parameterValue);
        }
        #endregion

        #region 辅助方法===================================
        /// <summary>
        /// 判断微信签名
        /// </summary>
        /// <returns></returns>
        public virtual bool isWXsign(out string error)
        {
            StringBuilder sb = new StringBuilder();
            Hashtable signMap = new Hashtable();
            foreach (string k in xmlMap.Keys)
            {
                if (k != "sign")
                {
                    signMap.Add(k.ToLower(), xmlMap[k]);
                }
            }

            ArrayList akeys = new ArrayList(signMap.Keys);
            akeys.Sort();

            foreach (string k in akeys)
            {
                string v = (string)signMap[k];
                sb.Append(k + "=" + v + "&");
            }
            sb.Append("key=" + this.key);

            Trace.TraceInformation("Notify 页面  返回数据：" + sb.ToString() + "、sign： " + xmlMap["sign"].ToString());

            string sign = SecureHelper.MD5(sb.ToString()).ToUpper();
            error = "sign = " + sign + "\r\n xmlMap[sign]=" + xmlMap["sign"].ToString();
            return sign.Equals(xmlMap["sign"]);

        }

        /// <summary>
        /// 判断微信维权签名
        /// </summary>
        /// <returns></returns>
        public virtual bool isWXsignfeedback()
        {
            return true;
        }



        /// <summary>
        /// 返回是否成功
        /// </summary>
        /// <returns></returns>
        public virtual bool IsSuccess()
        {
            return getParameter("return_code") == "SUCCESS" &&
                   getParameter("result_code") == "SUCCESS";
        }
        public virtual string GetErrMsg()
        {
            if (!string.IsNullOrEmpty(getParameter("err_code_des")))
                return getParameter("err_code_des");        //业务逻辑原因

            if (getParameter("return_code") != "SUCCESS")
                return getParameter("return_msg");          //通信原因
            return "error";
        }
        #endregion
    }
}